/*
 * @lc app=leetcode.cn id=5 lang=cpp
 *
 * [5] 最长回文子串
 *
 * https://leetcode.cn/problems/longest-palindromic-substring/description/
 *
 * algorithms
 * Medium (37.09%)
 * Likes:    5641
 * Dislikes: 0
 * Total Accepted:    1.2M
 * Total Submissions: 3.2M
 * Testcase Example:  '"babad"'
 *
 * 给你一个字符串 s，找到 s 中最长的回文子串。
 * 
 * 
 * 
 * 示例 1：
 * 
 * 
 * 输入：s = "babad"
 * 输出："bab"
 * 解释："aba" 同样是符合题意的答案。
 * 
 * 
 * 示例 2：
 * 
 * 
 * 输入：s = "cbbd"
 * 输出："bb"
 * 
 * 
 * 
 * 
 * 提示：
 * 
 * 
 * 1 <= s.length <= 1000
 * s 仅由数字和英文字母组成
 * 
 * 
 */

// @lc code=start
class Solution {
public:
    string longestPalindrome(string s) {
        int size = s.size();
        if(size == 1) return s;
        int countL = 0, countR = size-1;
        int len = 0;
        int max = 0;
        int ansL=0, ansR=0;
        while(countL < size) {
            bool res = check(s, countL, countR);
            if(res){
                len = countR - countL + 1;
                if(max < len) 
                {
                    ansL = countL;
                    ansR = countR;
                    max = len;
                }

            }
            if(max > size - countL);
            countR = size - 1;
            countL++;
        }
        // cout<<"ansL = "<<ansL<<" max = "<<max<<endl;
        return s.substr(ansL, max);
    }

    bool check(string s, int& left, int& right) {
        while(left < right) {
            while(s[left] != s[right]) right--;
            int i, j;
            for(i = left, j = right; i < j; i++, j--){
                if(s[i] != s[j]) break;
            }
            if (i >= j) return true;
            right--;
        }
        return false;
    }
};
// @lc code=end

